#!/usr/bin/python3
# -*- coding: utf-8 -*-


import aioredis
import aiohttp
import aiomysql
from ujson import dumps
from Alibb.settings import settings


async def _init_with_loop(loop):
    """
    redis 连接池
    aiohttp 连接池
    aiomysql 连接池
    :param loop: 循环
    :return: redis pool
    """

    __pool = await aioredis.create_redis_pool(settings['redis_url'],
                                              minsize=settings['redis_url_minsize'],
                                              maxsize=settings['redis_url_maxsize'],
                                              encoding='utf8',
                                              password=settings['redis_password'],
                                              loop=loop)

    __session = aiohttp.ClientSession(json_serialize=dumps)

    __mysql = await aiomysql.create_pool(host=settings['host'],
                                         port=settings['port'],
                                         user=settings['user'],
                                         password=settings['password'],
                                         loop=loop,
                                         autocommit=True,
                                         minsize=settings['mysql_minsize'],
                                         maxsize=settings['mysql_maxsize'])

    return __pool, __session, __mysql


class RedisPool:
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, "_instance"):
            _loop = kwargs.get("loop", None)
            assert _loop, "use get_event_loop()"
            cls._redis, cls._session, cls._mysql = _loop.run_until_complete(_init_with_loop(_loop))
            cls._instance = super(RedisPool, cls).__new__(cls)
        return cls._instance

    def get_conn(self) -> aioredis.Redis:
        return self._redis

    def get_aiohttp(self):
        return self._session

    def get_aiomysql(self):
        return self._mysql
